package com.sunagy.demand.front.service.impl;

import com.sunagy.demand.front.dataobject.AdminUser;
import com.sunagy.demand.front.dto.AdminUserDto;
import com.sunagy.demand.front.exception.AdminUserIncorrectPasswordException;
import com.sunagy.demand.front.exception.AdminUserNotFoundException;
import com.sunagy.demand.front.exception.UsernameExistException;
import com.sunagy.demand.front.repository.AdminUserRepository;
import com.sunagy.demand.front.service.AdminUserService;
import com.sunagy.demand.front.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/4/24
 * time：下午6:25
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUserRepository adminUserRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public AdminUserDto login(String username, String password) {
        AdminUser adminUser = adminUserRepository.findByUsername(username);
        if (adminUser == null){
            throw new AdminUserNotFoundException();
        }
        if(!passwordEncoder.matches(password, adminUser.getPassword())){
            throw new AdminUserIncorrectPasswordException();
        }
        AdminUserDto adminUserDto = new AdminUserDto();
        adminUserDto.setId(adminUser.getId());
        adminUserDto.setPassword(adminUser.getPassword());
        adminUserDto.setUsername(adminUser.getUsername());
        return adminUserDto;
    }

    @Override
    @Transactional
    public AdminUserDto add(AdminUser adminUser) {
        if (adminUserRepository.findByUsername(adminUser.getUsername()) != null){
            throw new UsernameExistException();
        }
        adminUser.setEnable(true);
        adminUser.setPassword(passwordEncoder.encode(adminUser.getPassword()));
        adminUser = adminUserRepository.save(adminUser);
        AdminUserDto adminUserDto = new AdminUserDto();
        adminUserDto.setId(adminUser.getId());
        adminUserDto.setUsername(adminUser.getUsername());
        return adminUserDto;
    }

    @Override
    public List<AdminUserDto> getAll() {
        List<AdminUserDto> adminUserDtoList = new ArrayList<>();
        adminUserDtoList = (List<AdminUserDto>) BeanUtil.copyPropertiesList(adminUserRepository.findAll(),AdminUserDto.class);
        return adminUserDtoList;
    }

}
